package com.sywb.chuangyebao.view.video;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.aliyun.vodplayer.media.AliyunLocalSource;
import com.aliyun.vodplayer.media.AliyunVodPlayer;
import com.aliyun.vodplayer.media.IAliyunVodPlayer;

import java.io.File;

/**
 * Created by duxl on 2018/5/21.
 */

public class PublishVideoPlayer {

    private Context mContext;
    private SurfaceView mSurfaceView;
    private AliyunVodPlayer mAliyunVodPlayer;
    private OnProgressChangeListner mOnProgressChangeListner;
    private IAliyunVodPlayer.OnPreparedListener mOnPreparedListener;

    private String mVideoPath;
    private int mPlayState; // 0 未设置视频源、1已设置视频源，2可以播放或正在播放中

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0) {
                callbackProgress();
                mHandler.sendEmptyMessageDelayed(0, 100);
            } else if(msg.what == 1) {
                play();
            }
        }
    };

    public PublishVideoPlayer(Context context, SurfaceView surfaceView) {
        this.mContext = context;
        mAliyunVodPlayer = new AliyunVodPlayer(mContext);
        mAliyunVodPlayer.disableNativeLog();
        setSurfaceView(surfaceView);
        initPalyerListener();
    }

    public void setSurfaceView(SurfaceView surfaceView) {
        mSurfaceView = surfaceView;
        mSurfaceView.getHolder().addCallback(new SurfaceHolderCallback(){
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                super.surfaceCreated(holder);
                mAliyunVodPlayer.setDisplay(holder);
            }
        });
        mAliyunVodPlayer.setDisplay(mSurfaceView.getHolder());
    }

    private void startTimer() {
        mHandler.sendEmptyMessage(0);
    }

    private void stopTimer() {
        if(mHandler != null) {
            mHandler.removeMessages(0);
        }
    }

    private void callbackProgress() {
        if(mOnProgressChangeListner != null) {
            int current = (int) mAliyunVodPlayer.getCurrentPosition();
            int total = (int) mAliyunVodPlayer.getDuration();
            mOnProgressChangeListner.onProgressChanged(current, total);
        }
    }

    public void setOnProgressChangeListner(OnProgressChangeListner listner) {
        this.mOnProgressChangeListner = listner;
    }

    public void setOnPreparedListener(IAliyunVodPlayer.OnPreparedListener listener) {
        this.mOnPreparedListener = listener;
    }

    /**
     * 获取视频播放状态
     * @return
     */
    public IAliyunVodPlayer.PlayerState getPlayerState() {
        return mAliyunVodPlayer.getPlayerState();
    }

    /**
     * 跳转到指定时间点的视频画面，时间单位为秒
     * @param position
     */
    public void seekTo(int position) {
        mAliyunVodPlayer.seekTo(position * 1000);
    }

    /**
     * 播放视频
     * @throws IllegalArgumentException 本地视频不存在也不是网络视频时会throw
     */
    public void play() {
        if(mPlayState == 0) {
            throw new IllegalArgumentException("未设置视频源或视频源不存在");
        }
        if(mPlayState == 1) {
            System.out.println("============= wait prepared to play ……");
            mHandler.sendEmptyMessageDelayed(1, 100);
            return;
        }
        IAliyunVodPlayer.PlayerState playerState = getPlayerState();
        if(playerState == IAliyunVodPlayer.PlayerState.Prepared
                || playerState == IAliyunVodPlayer.PlayerState.Paused) {
            mAliyunVodPlayer.start();
        } else if(playerState == IAliyunVodPlayer.PlayerState.Completed) {
            mAliyunVodPlayer.replay();
        }
        startTimer();
    }

    /**
     * 暂停播放
     */
    public void pause() {
        mHandler.removeMessages(1);
        stopTimer();
        IAliyunVodPlayer.PlayerState playerState = getPlayerState();
        if(playerState == IAliyunVodPlayer.PlayerState.Started) {
            mAliyunVodPlayer.pause();
        }
    }

    /**
     * 设置视频文件
     * @param path 视频文件路径
     */
    public void setSource(String path) {
        mPlayState = 0;
        mVideoPath = path;
        mHandler.removeMessages(1);

        if(!TextUtils.isEmpty(mVideoPath) && (TextUtils.indexOf(mVideoPath, "http") == 0 || new File(mVideoPath).exists())) {
            mPlayState = 1;
        }

        mAliyunVodPlayer.stop();
        mAliyunVodPlayer.setOnPreparedListener(new IAliyunVodPlayer.OnPreparedListener() {
            @Override
            public void onPrepared() {
                mPlayState = 2;
                System.out.println("============= wait prepared to play ……onPrepared");
                if(mOnPreparedListener != null) {
                    mOnPreparedListener.onPrepared();
                }
            }
        });
        AliyunLocalSource.AliyunLocalSourceBuilder asb = new AliyunLocalSource.AliyunLocalSourceBuilder();
        asb.setSource(path);
        AliyunLocalSource mLocalSource = asb.build();
        mAliyunVodPlayer.prepareAsync(mLocalSource);
    }

    private void initPalyerListener() {
//        mAliyunVodPlayer.setOnPreparedListener(new IAliyunVodPlayer.OnPreparedListener() {
//            @Override
//            public void onPrepared() {
//                //准备完成触发
//            }
//        });
        mAliyunVodPlayer.setOnFirstFrameStartListener(new IAliyunVodPlayer.OnFirstFrameStartListener() {
            @Override
            public void onFirstFrameStart() {
                //首帧显示触发
                callbackProgress();
            }
        });
        mAliyunVodPlayer.setOnErrorListener(new IAliyunVodPlayer.OnErrorListener() {
            @Override
            public void onError(int arg0, int arg1, String msg) {
                //出错时处理，查看接口文档中的错误码和错误消息
                stopTimer();
            }
        });
        mAliyunVodPlayer.setOnCompletionListener(new IAliyunVodPlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                //播放正常完成时触发
                callbackProgress();
                stopTimer();
            }
        });
        mAliyunVodPlayer.setOnSeekCompleteListener(new IAliyunVodPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete() {
                //seek完成时触发
                //play();
            }
        });
        mAliyunVodPlayer.setOnStoppedListner(new IAliyunVodPlayer.OnStoppedListener() {
            @Override
            public void onStopped() {
                //使用stop功能时触发
            }
        });
        mAliyunVodPlayer.setOnChangeQualityListener(new IAliyunVodPlayer.OnChangeQualityListener() {
            @Override
            public void onChangeQualitySuccess(String finalQuality) {
                //视频清晰度切换成功后触发
            }
            @Override
            public void onChangeQualityFail(int code, String msg) {
                //视频清晰度切换失败时触发
            }
        });
        mAliyunVodPlayer.setOnCircleStartListener(new IAliyunVodPlayer.OnCircleStartListener(){
            @Override
            public void onCircleStart() {
                //循环播放开始
            }
        });
    }

    class SurfaceHolderCallback implements SurfaceHolder.Callback {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            mAliyunVodPlayer.setDisplay(holder);
        }
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {mAliyunVodPlayer.surfaceChanged();}
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        }
    }

    /**
     * 播放进度监听
     */
    public interface OnProgressChangeListner {
        /**
         * 播放进度监听改变
         * @param current 当前进度（毫秒）
         * @param total 视频总时间（毫秒）
         */
        void onProgressChanged(int current, int total);
    }
}
